import os
import json
import itchat
from itchat.content import TEXT
import time

class _weixin:
    def __init__(self):
        self.qrcodeurl = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/static/weixin/'
        self.statusStorageDir = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '/data/weixin/hupan.pkl'
        self.islogin = False
        self.uuid = ''
        self.userInfo = ''
        itchat.useHotReload, itchat.hotReloadDir = True, self.statusStorageDir
        self.check_login()

    def getQr(self):
        '''
        获取二维码
        :return:
        '''
        self.uuid = itchat.get_QRuuid()
        while self.uuid is None: self.uuid = itchat.get_QRuuid();time.sleep(1)
        qrcodeurlname = str(int(time.time()))+'.png'
        itchat.get_QR(self.uuid,enableCmdQR=False,picDir=self.qrcodeurl+qrcodeurlname,isopen=False)
        return qrcodeurlname

    def check_login(self):
        if itchat.load_login_status(self.statusStorageDir):
            self.islogin=True
            return True
        else:
            self.islogin = False
            return False

    def search_friends(self,nickName='.1世の约定',field=None):
        '''
        :param nickName:
        :param field: UserName
        :return: info
        '''
        me = itchat.search_friends(nickName=nickName)[0]
        if field and field in me:
            return me[field]
        else:
            return me


    def wxsend(self,msg,toUserName=None):
        if toUserName:
            user = self.search_friends(field='UserName')
        else:
            user = 'filehelper'

        itchat.send(msg, toUserName=user)

    def jsonmsg(self,msg,code=1):
        jsonData = {'code':code,'msg':msg}
        jsonData = json.dumps(jsonData)
        return jsonData

    def getMyInfo(self):
        self.userInfo = itchat.web_init()
        itchat.update_friend(self.userInfo['User']['UserName'])
        data = {'NickName': self.userInfo['User']['NickName'],
                'HeadImgUrl': 'https://wx.qq.com' + self.userInfo['User']['HeadImgUrl']}
        return data

    def tologin(self):
        waitForConfirm = False
        while 1:
            status = itchat.check_login(self.uuid)
            if status == '200':
                self.userInfo = itchat.web_init()
                itchat.show_mobile_login()

                itchat.get_friends(True)
                itchat.dump_login_status(self.statusStorageDir)
                # print(userInfo)

                return self.jsonmsg('登录成功')
            elif status == '201':
                if waitForConfirm:
                    waitForConfirm = True
                    return self.jsonmsg('Please press confirm', 3)
            elif status == '408':
                waitForConfirm = False
                return self.jsonmsg('Reloading QR Code', 2)

    def logout(self):
        itchat.logout()